<template>
  <section>
    <div class="tableBlock" ref="tableBlock">
      <div class="tableScroll">
        <a-table
          :rowSelection="isShowSelection()"
          :columns="tableConfig.columns"
          :data-source="tableData.records"
          :pagination="false"
          size="middle"
          :rowKey="
            (record, index) => {
              return index;
            }
          "
          bordered
          :customRow="handleClickRow"
          :rowClassName="rowClassName"
          :scroll="{ x: tableConfig.scrollX, y: useScrollY() }"
        >
          <template slot="isYesNo" slot-scope="text">
            <a-tag :color="isYesNo(text, 'color')">
              {{ isYesNo(text) }}
            </a-tag>
          </template>
          <template slot="status" slot-scope="text">
            <a-tag v-if="text != null" :color="isEnableShow(text, 'color')">
              {{ isEnableShow(text) }}
            </a-tag>
          </template>
          <template slot="action" slot-scope="text, record">
            <slot :text="text" :record="record">无插槽数据</slot>
          </template>
        </a-table>
      </div>
    </div>
    <div class="emptyLine"></div>
    <div class="paginationBlock">
      <a-pagination
        v-model="currentPage"
        :page-size-options="usePageSizeOptions()"
        :show-total="(total) => `共 ${useTotalElements()} 条`"
        :total="useTotalElements()"
        show-size-changer
        :page-size="pageSize"
        @change="handleCurrentPageChange"
        @showSizeChange="handlePageSizeChange"
      >
      </a-pagination>
      <span>跳至</span>
      <a-input-number class="jumpTo" v-model="number" :min="1" @change="jumpToPage" />
      <span>页</span>
    </div>
  </section>
</template>

<script>
import { getIsEnableOption, getYesNo } from '@/utils/frequentInterface';
import Button from '@/components/typicalControl/button';
export default {
  name: 'TypicalName',
  components: {
    Button,
  },
  props: {
    tableConfig: {
      type: Object,
      default: () => {
        return {
          columns: [
            {
              title: '未定义栏',
              dataIndex: 'name',
              key: 'name',
            },
          ],
        };
      },
    },
    tableData: {
      type: Object,
      default: () => {
        return {
          records: [],
          total: 0,
        };
      },
    },
    // 是否需要点击行
    isRowClick: {
      type: Boolean,
      default: false,
    },
  },
  computed: {
    totalElements() {
      return this.tableData.total;
    },
  },
  watch: {
    totalElements() {
      // 注意：因为总信息动态业务判断，所以手动清空列表要放到接口报错后处理，不能先重置
      if (this.judgeShowListEmpty()) {
        this.currentPage -= 1;
        this.handleCurrentPageChange();
      }
    },
    tableData: {
      handler: function (cur, old) {
        this.selectedRowKeys = [];
        this.selectedRows.forEach((item) => {
          cur.records.forEach((pp, index) => {
            if (item.id == pp.id) {
              this.selectedRowKeys.push(index);
            }
          });
        });
        this.$emit('selectionChange', this.selectedRowKeys, this.selectedRows);
      },
      deep: true, //对象内部的属性监听，也叫深度监听
      immediate: true,
    },
  },
  data() {
    return {
      currentPage: 1,
      pageSize: 10,
      pageSizeOptions: ['5', '10', '15', '20'],
      selectedRowKeys: [],
      selectedRows: [],
      sort: ['createTime,desc'],
      timer: null,
      keyboardEvent: null,
      number: null,
      numberAgain: null,
      currentTableHeight: null,
    };
  },
  created() {
    this.Initialization();
  },
  methods: {
    /**
     * [useScrollY 使用列表Y轴高度]
     * @param  {Boolean} isUpdate [是否更新获取当前table高度]
     * @return {[type]}           [description]
     */
    useScrollY(isUpdate) {
      if (isUpdate) {
        this.currentTableHeight = this.$refs.tableBlock.offsetHeight;
      }
      var result = null;
      if (this.tableConfig.scrollX && !this.tableConfig.scrollY && this.currentTableHeight) {
        result = this.currentTableHeight - 80;
        if (result < 0) {
          result = null;
        }
      } else if (this.tableConfig.scrollY) {
        result = this.tableConfig.scrollY;
      }
      return result;
    },
    /**
     * [isShowSelection 判断是否table显示多选框]
     * @return {Boolean} [description]
     */
    isShowSelection() {
      if (this.tableConfig.isSelection) {
        return {
          selectedRowKeys: this.selectedRowKeys,
          onChange: this.onSelectChange,
          onSelect: this.onSelect,
          onSelectAll: this.onSelectAll,
        };
      } else {
        return null;
      }
    },
    onSelect(record, selected, selectedRows) {
      if (selected) {
        this.selectedRows.push(record);
      }

      if (!selected) {
        const delIndex = this.selectedRows.findIndex((val) => {
          return val.id === record.id;
        });
        this.selectedRows.splice(delIndex, 1);
      }
      this.$emit('selectionChange', this.selectedRowKeys, this.selectedRows);
    },
    onSelectAll(selected, selectedRows, changeRows) {
      if (selected) {
        this.selectedRows = this.selectedRows.concat(changeRows);
      }
      if (!selected) {
        let selectedRows = JSON.parse(JSON.stringify(this.selectedRows));
        const delIndex = [];
        selectedRows.forEach((item, index) => {
          changeRows.forEach((val, itemIndex) => {
            if (item.id === val.id) {
              delIndex.push(index);
            }
          });
        });
        delIndex.forEach((item) => {
          delete selectedRows[item];
        });
        selectedRows = selectedRows.filter((item) => {
          return item !== undefined;
        });
        this.selectedRows = selectedRows;
      }
      this.$emit('selectionChange', this.selectedRowKeys, this.selectedRows);
    },
    /**
     * [onSelectChange 多选框变化回调]
     * @param  {[type]} selectedRowKeys [多选id数组]
     * @param  {[type]} selectedRows    [多选obj数组]
     * @return {[type]}                 [description]
     */
    onSelectChange(selectedRowKeys, selectedRows) {
      // console.log('table', selectedRowKeys, selectedRows);
      this.setSelectedRowKeys(selectedRowKeys);
      this.$emit('selectionChange', this.selectedRowKeys, selectedRows);
    },
    /**
     * [setSelectedRowKeys 设置选中的多选框数据]
     * @param {[type]} selectedRowKeys [多选数组]
     */
    setSelectedRowKeys(selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys;
    },
    /**
     * [judgeShowListEmpty 判断当前页码列表显示是否为空]
     * @return {[type]} [description]
     */
    judgeShowListEmpty() {
      var result = false;
      if (this.currentPage > 1 && (this.currentPage - 1) * this.pageSize > this.tableData.total) {
        result = true;
      }
      return result;
    },
    /**
     * [Initialization 初始化组件配置生成页码初始值]
     */
    Initialization() {
      if (this.tableConfig.currentPage) this.currentPage = this.tableConfig.currentPage;
      if (this.tableConfig.pageSize) this.pageSize = this.tableConfig.pageSize;
    },
    /**
     * [usePageSizeOptions 使用分页选项]
     * @return {[type]} [description]
     */
    usePageSizeOptions() {
      return this.tableConfig.pageSizeOptions ? this.tableConfig.pageSizeOptions : this.pageSizeOptions;
    },
    /**
     * [useTotalElements 使用的总消息条数]
     * @return {[type]} [description]
     */
    useTotalElements() {
      return this.tableData.total ? this.tableData.total : 0;
    },
    /**
     * [updateListData 更新列表数据]
     * @return {[type]} [description]
     */
    updateListData(isDelete) {
      // 清空已选项
      this.onSelectChange([], []);
      var searchParam = {};
      if (this.tableConfig.parent && this.tableConfig.parent.$refs.insideSearch) {
        const search = this.tableConfig.parent.$refs.insideSearch._getSearchData();
        Object.assign(searchParam, search);
      }
      // 页码组件与列表参数差1
      if (isDelete) {
        //执行删除操作时，若当前页只有一条数据，删除成功后，查询上一页数据
        searchParam.pageNumber =
          this.tableData.records.length == 1 && this.currentPage > 1 ? this.currentPage - 2 : this.currentPage - 1;
      } else {
        searchParam.pageNumber = this.currentPage - 1;
      }
      
      searchParam.pageSize = this.pageSize;
      searchParam.sort = this.sort;
      this.$emit('getTableData', searchParam);
      // if (document.querySelector('.ant-pagination-options-quick-jumper input')) {
      //   clearTimeout(this.timer);
      //   this.timer = setTimeout(() => {
      //     document.querySelector('.ant-pagination-options-quick-jumper input').value = '';
      //   }, 1000);
      // }
    },
    /**
     * [jumpToPage 跳转页面]
     * @param  {[type]} num [页码]
     * @return {[type]}     [description]
     */
    jumpToPage(num) {
      if (num === this.numberAgain) {
        if (this.currentPage !== num) {
          const maxPage = Math.ceil(this.totalElements / this.pageSize);
          this.currentPage = num <= maxPage ? num : maxPage;
          this.updateListData();
        }
      }
      this.numberAgain = num;
      this.number = null;
    },
    /**
     * [handleCurrentPageChange 页码改变]
     * @return {[type]}          [description]
     */
    handleCurrentPageChange() {
      this.updateListData();
    },
    /**
     * [handlePageSizeChange 分页改变]
     * @param  {[type]} page     [页码]
     * @param  {[type]} pageSize [分页]
     * @return {[type]}          [description]
     */
    handlePageSizeChange(page, pageSize) {
      // 页码改变分页归1
      this.currentPage = 1;
      this.pageSize = pageSize;
      this.handleCurrentPageChange();
    },
    /**
     * [setCurrentPage 设置当前页码]
     * @param {[type]} search [description]
     */
    setCurrentPage(search) {
      if ((search && search.pageNumber) || search.pageNumber === 0) {
        this.currentPage = search.pageNumber + 1;
      }
    },
    /**
     * [rowClassName 根据行内容决定行样式名称]
     * @param  {[type]} record [行数据]
     * @param  {[type]} index  [序号（0起）]
     * @return {[type]}        [description]
     */
    rowClassName(record, index) {
      let className = 'enableBackground';
      if (index % 2 === 0) className = 'deactivateBakcground';
      if (this.tableData.records[index].active) className = 'activeClass';
      return className;
    },
    handleClickRow(record, index) {
      return {
        on: {
          click: () => {
            if (this.isRowClick) {
              this.tableData.records.forEach((ele) => {
                ele.active = false;
              });
              this.tableData.records[index].active = true;
            }
            this.$emit('rowEmit', record);
          },
        },
      };
    },
    /**
     * [_getTableData 得到列表条件信息（专供search组件使用）]
     * @return {[type]} [description]
     */
    _getTableData() {
      // 清空已选项
      this.onSelectChange([], []);
      const dataJson = {
        pageNumber: this.currentPage - 1,
        pageSize: this.pageSize,
        sort: this.sort,
      };
      return dataJson;
    },
    /**
     * [isEnableShow 启用状态显示]
     * @param  {[type]}  val       [值]
     * @param  {[type]}  attribute [查询字段属性（空为name）]
     * @return {Boolean}           [description]
     */
    isEnableShow(val, attribute = 'name') {
      var result = val;
      const arr = getIsEnableOption();
      if (arr) {
        for (var i = 0; i < arr.length; i++) {
          if (arr[i].code == +val) {
            result = arr[i][attribute];
            break;
          }
        }
      }
      return result;
    },
    /**
     * [isYesNo 是否状态显示]
     * @param  {[type]}  val       [值]
     * @param  {String}  attribute [查询字段属性（空为name）]
     * @return {Boolean}           [description]
     */
    isYesNo(val, attribute = 'name') {
      var result = val;
      const arr = getYesNo();
      if (arr) {
        for (var i = 0; i < arr.length; i++) {
          if (arr[i].code == +val) {
            result = arr[i][attribute];
            break;
          }
        }
      }
      return result;
    },
  },
  mounted() {
    window.onresize = () => {
      return (() => {
        this.useScrollY(true);
      })();
    };
    this.useScrollY(true);
  },
  destroyed() {
    window.onresize = null;
  },
};
</script>

<style scoped>
.tableBlock {
  width: 100%;
  background: #fff;
  padding: 5px 10px;
  min-height: calc(100vh - 350px);
}
.emptyLine {
  width: 100%;
  height: 10px;
  background: #f0f2f5;
}
.paginationBlock {
  width: 100%;
  background: #fff;
  padding: 10px 10px;
  display: flex;
  align-items: center;
  justify-content: flex-end;
}
.jumpTo {
  margin: 0 5px;
  width: 50px;
}
</style>
<style>
.tableBlock .deactivateBakcground {
  cursor: pointer;
  background: white !important;
}
.tableBlock .enableBackground {
  cursor: pointer;
  background: #fafafa !important;
}
.tableBlock .activeClass {
  cursor: pointer;
  background: #bae7ff !important;
}
</style>
